package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;

import utils.BidsHelper;
import entities.Bid;

/**
 * Servlet implementation class BitsServlets
 */
@WebServlet("/Bids")
public class BidsServlets extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String MONEY = "money";
	private static final String BIDS = "bids";
    private static final String NEW_CURRENT_BIT_AMOUNT= "newCurrentBidAmount";
   
    public BidsServlets() {
        super();
        // TODO Auto-generated constructor stub
    }

    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json");
		response.setStatus(200);
		
		List<Bid> bidsList = BidsHelper.getBids(
				ServletsUtil.getUserID(request), 
				ServletsUtil.getPageNumber(request, response),
				ServletsUtil.getStartFrom(request, response)
				);
		
			ObjectMapper mapper = new ObjectMapper();
			PrintWriter writer = response.getWriter();
			writer.write(
						"{\"" + BIDS +"\":" + mapper.writeValueAsString(bidsList) + "}"					
						);
			writer.flush();
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Bid bid = getBid(request);
		double newCurrentBitAmount = BidsHelper.postBid(bid);
		response.setContentType("text/json");
		try {
			response.getWriter().write(
					new JSONObject().put(ServletsUtil.RESULT, newCurrentBitAmount != -1).
					put(NEW_CURRENT_BIT_AMOUNT,newCurrentBitAmount).toString()
					);
		} catch (JSONException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}



	private static Bid getBid(HttpServletRequest request) {
		Bid bid = new Bid();
		JSONObject jsonObject ;
		String str = null;
		
		try {
			str = request.getReader().readLine();
			jsonObject = new JSONObject(str);
					bid.setItemID(jsonObject.optLong(ItemsServlet.ITEM_ID));
					bid.setUserID(ServletsUtil.getUserID(request));
					bid.setMoney(jsonObject.optDouble(MONEY));
			return bid;
		}catch (JSONException | IOException e){
			e.printStackTrace();
		}
		return null;
	}

}
